import {NIcon} from "naive-ui";

/**
 *  渲染图标的函数
 * @param icon
 * @returns {function(): VNode<RendererNode, RendererElement, {[p: string]: any}>}
 */
export const renderIcon = (icon) => {
    return () => h(NIcon, null, {default: () => h(icon)})
}

/**
 * 将路由数组转换为 Naive UI 菜单配置
 * @param {Array} routes - Vue Router 路由配置
 * @returns {Array} - Naive UI 菜单配置
 */
export function transformRoutesToMenu(routes) {
    return routes
        .filter(route => !(route.meta && route.meta.hidden)) // 过滤 hidden = true 的路由
        .map(route => {
            const menu = {
                key: route.name,
                label: route.meta ? route.meta.title : '',
                icon: route.meta && route.meta.icon ? renderIcon(route.meta.icon) : undefined
            }

            if (route.children && route.children.length > 0) {
                menu.children = transformRoutesToMenu(route.children)
            }

            return menu
        })
}

// 过滤有权限的路由
export function filterRoutesByPermission(routes, userPermissions) {
    if (!userPermissions || userPermissions.length === 0) {
        return []
    }
    return routes.filter(route => {
        // 如果是超级管理员，直接通过
        if (userPermissions.includes('*')) {
            return true
        }
        // 如果路由有权限要求，检查用户是否有权限
        if (route.meta && route.meta.permission) {
            if (!userPermissions.includes(route.meta.permission)) {
                return false
            }
        }
        // 递归过滤子路由
        if (route.children && route.children.length > 0) {
            route.children = filterRoutesByPermission(route.children, userPermissions)
        }
        return true
    })
}

/**
 * 通用权限检查函数
 * @param key
 * @param actions
 * @param userPermissions
 * @returns {*|boolean}
 */
export function checkPermission(key, actions, userPermissions) {
    if (!key) return false;
    if (userPermissions.includes("*")) return true;

    const perm = actions[key];
    if (!perm) return false;

    return userPermissions.includes(perm);
}

/**
 * 把 routes 转换成 菜单权限树
 * @param {Array} routes 路由配置
 * @returns {Array} 菜单+权限树
 */
export function convertRoutesToMenuPermissionTree(routes) {
    return routes.map(route => {
        const node = {
            name: route.meta?.title,
            permission: route.meta?.permission,
        };

        // 如果有 actions，保留
        if (route.meta?.actions) {
            node.actions = { ...route.meta.actions };
        }

        // 如果有 children，递归处理
        if (route.children && route.children.length > 0) {
            node.children = convertRoutesToMenuPermissionTree(route.children);
        }

        return node;
    });
}

